

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" type="image/png" href="/img/favicon.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="">
  <meta name="keywords" content="">
  <title>文件上传与下载 - Hexo</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10.4.0/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" />
  



<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.8.6","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"copy_btn":true,"image_zoom":{"enable":true},"lazyload":{"enable":true,"onlypost":false},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null}}};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.3.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>yun&bo</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/index01.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="文件上传与下载">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-12-20 22:54" pubdate>
        2020年12月20日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      588 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      9
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">文件上传与下载</h1>
            
            <div class="markdown-body">
              <p>SpringMVC使用异步上传</p>
<h2 id="ajax异步上传文件">ajax异步上传文件</h2>
<h4 id="添加依赖">添加依赖</h4>
<ol>
<li>commons-fileupload</li>
<li>jackson-databind</li>
</ol>
<h3 id="所需资源文件">所需资源文件</h3>
<ol>
<li>jquery：迅捷开发</li>
<li>layer：弹窗插件</li>
<li>jquery.uploadfive 上载插件</li>
</ol>
<h3 id="WEB-配置">WEB 配置</h3>
<h4 id="ContextLoaderListener">ContextLoaderListener</h4>
<ol>
<li>指定Web程序启动时装载IOC容器</li>
</ol>
<h4 id="DispatcherServlet">DispatcherServlet</h4>
<ol>
<li>DispatcherSevlet负责将请求分发，所有的请求都有经过它来统一分发。</li>
<li>负责装载 Controller</li>
</ol>
<h3 id="SpringMVC特殊配置">SpringMVC特殊配置</h3>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><br>&lt;bean id=<span class="hljs-string">&quot;multipartResolver&quot;</span> <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;</span>&gt;<br>     &lt;!-- 默认编码 --&gt;<br>     &lt;property name=<span class="hljs-string">&quot;defaultEncoding&quot;</span> value=<span class="hljs-string">&quot;utf-8&quot;</span>/&gt;<br>     &lt;!-- 文件大小最大值 --&gt;<br>     &lt;property name=<span class="hljs-string">&quot;maxUploadSize&quot;</span> value=<span class="hljs-string">&quot;10485760000&quot;</span>/&gt;<br>     &lt;!-- 内存中的最大值 --&gt;<br>     &lt;property name=<span class="hljs-string">&quot;maxInMemorySize&quot;</span> value=<span class="hljs-string">&quot;40960&quot;</span>/&gt;<br> &lt;/bean&gt;<br></code></pre></div></td></tr></table></figure>
<h3 id="ajax代码">ajax代码</h3>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">//绑定进新增按钮事件</span><br>  $(<span class="hljs-string">&#x27;#but_&#x27;</span>).on(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>&#123;<br>      $.ajax(&#123;<br>          url: <span class="hljs-string">&#x27;user/form&#x27;</span>,<br>          type: <span class="hljs-string">&#x27;get&#x27;</span>,<br>          success: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">formHTML</span>) </span>&#123;<br>              layer.open(&#123;<br>                  type: <span class="hljs-number">1</span>,<br>                  title: <span class="hljs-string">&#x27;自动上传&#x27;</span>,<br>                  area: [<span class="hljs-string">&#x27;500px&#x27;</span>, <span class="hljs-string">&#x27;300px&#x27;</span>],<br>                  content: formHTML,<br>                  success: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">layer, index</span>) </span>&#123;<span class="hljs-comment">//弹窗后的回调</span><br>				<span class="hljs-comment">//调用上传函数</span><br>				buildUpload();<br>                  &#125;<br>              &#125;)<br>          &#125;<br>      &#125;)<br>  &#125;);<br></code></pre></div></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript"><span class="hljs-comment">//执行文件上传的函数</span><br><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buildUpload</span>(<span class="hljs-params"></span>) </span>&#123;<br>    <span class="hljs-comment">//绑定ajax上传文件</span><br>    $(<span class="hljs-string">&#x27;#userFile&#x27;</span>).uploadifive(&#123;<br>        <span class="hljs-string">&#x27;auto&#x27;</span>: <span class="hljs-literal">true</span>,<span class="hljs-comment">//是否自动上传 ，</span><br>        <span class="hljs-string">&#x27;fileObjName&#x27;</span>: <span class="hljs-string">&#x27;userFile&#x27;</span>,<span class="hljs-comment">//上传的二进制数据的名称</span><br>        <span class="hljs-string">&#x27;buttonText&#x27;</span>: <span class="hljs-string">&#x27;用户图像&#x27;</span>,<br>        <span class="hljs-string">&#x27;fileType&#x27;</span>: <span class="hljs-string">&#x27;image/*&#x27;</span>,<span class="hljs-comment">//上传文件的类型 image/png,image/jpg,image/gif</span><br>        <span class="hljs-string">&#x27;uploadScript&#x27;</span>: <span class="hljs-string">&#x27;user/upload&#x27;</span>,<span class="hljs-comment">//上传的URL</span><br>        <span class="hljs-string">&#x27;onUploadComplete&#x27;</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">file, data</span>) </span>&#123;<span class="hljs-comment">//上传成功后的回调</span><br>            $(<span class="hljs-string">&#x27;#userHead&#x27;</span>).val(data);<br>        &#125;,<br>    &#125;);<br>&#125;<br><br></code></pre></div></td></tr></table></figure>
<h4 id="Controller-处理请求">Controller 处理请求</h4>
<ul>
<li>SpringMVC提供了MultipartFile类型参数，可以直接获得浏览器发起的上传请求
<ul>
<li>转发参数MultiparFile 和 realPath</li>
<li>：request.getServletContext().getRealPath(�/�)  Web根目录绝对路径 ， 这个请求路径不是你的源码路径，而是服务器加载后生成的</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript">@PostMapping(<span class="hljs-string">&quot;/upload&quot;</span>)<br>public <span class="hljs-built_in">String</span> <span class="hljs-function"><span class="hljs-title">doUpload</span>(<span class="hljs-params">MultipartFile userFile, HttpServletRequest request</span>)</span> &#123;<br>	<br>    <span class="hljs-built_in">String</span> realPath = request.getServletContext().getRealPath(<span class="hljs-string">&quot;/&quot;</span>);<br>    <span class="hljs-keyword">return</span> userService.doUploadAvatar(userFile, realPath);<br>&#125;<br>	<br></code></pre></div></td></tr></table></figure>
<ul>
<li>输出到本地磁盘<br>
public final static String PATH_BASE = �upfiles/�;<br>
//用户图像的基本路径<br>
public final static String PATH_AVATAR = PATH_BASE + �avatar�;</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs javascript">@Override<br>   public <span class="hljs-built_in">String</span> <span class="hljs-function"><span class="hljs-title">doUploadAvatar</span>(<span class="hljs-params">MultipartFile partFile, <span class="hljs-built_in">String</span> realPath</span>)</span> &#123;<br>       <span class="hljs-keyword">if</span> (!partFile.isEmpty()) &#123;<br>           <span class="hljs-built_in">String</span> fileName = partFile.getOriginalFilename();<br>           <span class="hljs-comment">//build上传文件的相对路径</span><br>           StringBuilder filePath = <span class="hljs-keyword">new</span> StringBuilder(ConfigUtil.PATH_AVATAR);<br>           filePath.append(<span class="hljs-string">&quot;/&quot;</span>).append(Calendar.getInstance().getTimeInMillis()) .append(fileName.substring(fileName.lastIndexOf(<span class="hljs-string">&quot;.&quot;</span>)));<br>           File toFile = <span class="hljs-keyword">new</span> File(realPath + filePath);<br>           <span class="hljs-comment">//尝试生成文件夹</span><br>           File parentFile = toFile.getParentFile();<br>           <span class="hljs-keyword">if</span> (!parentFile.exists()) &#123;<br>               parentFile.mkdirs();<br>           &#125;<br>           <span class="hljs-keyword">try</span> &#123;<br>               partFile.transferTo(toFile);<br>           &#125; <span class="hljs-keyword">catch</span> (IllegalStateException | IOException e) &#123;<br>               e.printStackTrace();<br>           &#125;<br>           <span class="hljs-keyword">return</span> filePath.toString();<br>       &#125;<br>       <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;<br>   &#125;<br></code></pre></div></td></tr></table></figure><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/WEB/">WEB</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/12/21/Spring-Handler%E7%AE%80%E5%8D%95%E4%BD%BF%E7%94%A8/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Spring-Handler简单使用</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/12/20/SpringMVC%E5%8E%9F%E7%90%86/">
                        <span class="hidden-mobile">SpringMVC原理</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://gitee.com/YunBoZhang" target="_blank" rel="nofollow noopener"><span>Gitee</span></a> <i class="iconfont icon-love"></i> <a href="https://gitee.com/YunBoZhang" target="_blank" rel="nofollow noopener"><span>Gitee</span></a> 
  </div>
  

  

  
</footer>

<!-- SCRIPTS -->

  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":200})
    NProgress.start()
    document.addEventListener('DOMContentLoaded', function() {
      window.NProgress && window.NProgress.inc();
    })
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script  src="https://cdn.jsdelivr.net/npm/tocbot@4.12.0/dist/tocbot.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4.3.0/anchor.min.js" ></script>



  <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js" ></script>






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2.0.11/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    (function () {
      var path = "/local-search.xml";
      var inputArea = document.querySelector("#local-search-input");
      inputArea.onclick = function () {
        searchFunc(path, 'local-search-input', 'local-search-result');
        this.onclick = null
      }
    })()
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>



</body>
</html>
